// "Connect" button handler.
async function connect() {
    const url = document.getElementById('url').value;
    OnClose(() => {
        addToEventLog("连接断开")
    })
    On("PING", (header, body) => {
        let now = Date.now()
        addToEventLog(new Date().toLocaleTimeString() + " server -> client " + (now - parseInt(body)).toString() + " ms")
    })
    On("PONG", (header, body) => {
        let now = Date.now()
        addToEventLog(new Date().toLocaleTimeString() + " client -> client " + (now - parseInt(body)).toString() + " ms")
    })
    await Connect(url)
    document.forms.sending.elements.send.disabled = false;
    document.getElementById('connect').disabled = true;
}

// "Send data" button handler.
async function sendData() {
    setInterval(() => {
        Emit("PING", Date.now())
    }, 1000)
}

function addToEventLog(text, severity = 'info') {
    let log = document.getElementById('event-log');
    let mostRecentEntry = log.lastElementChild;
    let entry = document.createElement('li');
    entry.innerText = text;
    entry.className = 'log-' + severity;
    log.appendChild(entry);

    // If the most recent entry in the log was visible, scroll the log to the
    // newly added element.
    if (mostRecentEntry != null && mostRecentEntry.getBoundingClientRect().top < log.getBoundingClientRect().bottom) {
        entry.scrollIntoView();
    }
}


